#!/usr/bin/perl -w

use PDF::API2;

use constant mm => 25.4/72;
use constant in =>    1/72;
use constant pt =>    1;

$numArgs = $#ARGV + 1;
if ($numArgs != 2) {
  print "iliadPDF <source> <dest>\n";
  exit();
}

$source = $ARGV[0];
$dest   = $ARGV[1];

$sourcePDF = PDF::API2->new;
$sourcePDF = PDF::API2->open($source);
$target = PDF::API2->new;
$sourcePDF_page_count = $sourcePDF->pages;

#The cropbox takes left, bottom, right and top (in that order).
# Letter is 21.59 cm wide and 27.94 tall
# half of the height is 13.97

#           right
# ----------------------------
# |                          |
# |                          |
# |                          |
# | top                      | bottom
# |                          |
# |         left             |
# ----------------------------

#$width = 215.9/mm;
$height = 279.4/mm;

print "PAGE COUNT: $sourcePDF_page_count\n";

for $pagenum (0 ... ($sourcePDF_page_count - 1)) {
  my @slice = 0 ... 2;
    for $i (@slice) {
      #print "Slicing $i\n";
      #$page = $target->importpage($sourcePDF,$pagenum+1); 
      
      print "Importing " . ($pagenum + 1) . "\n";
      $xo = $target->importPageIntoForm($sourcePDF,$pagenum + 1);
      $page = $target->page;
      $gfx = $page->gfx;
      ## xo, shift right, shift up, scale
      $gfx->formimage($xo,30/mm,55/mm,0.75);
      
      $page->rotate(-90);
      $left = 10/mm;
      $right = 205.9/mm;
 
      $top = 279.4/mm - ($i * 71.96/mm);
      $bottom = $top - $height/2;

      #print " " . ($pagenum+1) . " $i: $top $bottom\n";

      $page->cropbox ( $left, $bottom, $right, $top); 
    }
  }
 
$target->saveas($dest);
print "Saved $dest\n";
 
